<?php
/**
 *      [迷你云] (C)2009-2012 南京恒为网络科技.
 *   软件仅供研究与学习使用，如需商用，请访问www.miniyun.cn获得授权
 * 
 */
?>
<?php


class MDbManager
{
    private $con;
    
    
    static private $_instance = null;

    
    private function  __construct() {
        $this->con = mysql_connect(DB_HOST.":".DB_PORT, DB_USER, DB_PASSWORD);
        mysql_set_charset(DB_CHARSET,$this->con);
        if (!$this->con)
        {
            die('Could not connect: ' . mysql_error());
        }
        
                                mysql_select_db(DB_NAME, $this->con);
    }

    
    static public function getInstance() {
        if (is_null(self::$_instance) || !isset(self::$_instance)) {
            self::$_instance = new self();
        }
        return self::$_instance;
    }
    
    
    function begin(){
         $null = mysql_query("START TRANSACTION", $this->con);
      return mysql_query("BEGIN", $this->con);
    }
    
    function commit(){
      return mysql_query("COMMIT", $this->con);
    }
    
    function rollback(){
      return mysql_query("ROLLBACK", $this->con);
    } 
    
    
    public function getCon() {
        return $this->con;
    }

    
    public function closeDb() {
        if (!$this->con){
            return null;
        }
        mysql_close($this->con);
    }

    
    public function insertDb($sql) 
    {
        $result = mysql_query($sql, $this->con);
        if ($result === false)
        {
            $message  = 'Invalid query: ' . mysql_error($this->con) . "\n";
            $message .= 'Whole query: ' . $sql;
            FXP::log($message, MLogger::LEVEL_WARNING);
        }

        return $result;
    }

    
    public function selectDb($sql) 
    {
        $result = mysql_query($sql, $this->con);

        $ret_array = array();
        if ($result === false)
        {
            $message  = 'Invalid query: ' . mysql_error($this->con) . "\n";
            $message .= 'Whole query: ' . $sql;
            FXP::log($message, MLogger::LEVEL_WARNING);
            return $ret_array;
        }

        while ($row = mysql_fetch_assoc($result))
        {
            array_push($ret_array, $row);
        }
        
                                mysql_free_result($result);

        return $ret_array;
    }

    
    public function updateDb($sql) {
        $result = mysql_query($sql, $this->con);
        if ($result === false)
        {
            return false;
        }

        return true;
    }

    
    public function deleteDb($sql) {
        mysql_query($sql, $this->con);
    }
    
    
    public function save_log_info($level, $message, $category, $log_key="common", $spend_time=0, $is_update=false) {
        if (!$is_update) {
            $create_at = new DateTime("now", new DateTimeZone('Asia/Shanghai'));
            $create_at = $create_at->format("Y-m-d H:i:s");
            $sql = "INSERT INTO log_infos(log_key, log_level, msg, category, created_at)";
            $sql .= " VALUES (\"{$log_key}\", \"{$level}\", \"{$message}\", \"{$category}\", \"{$create_at}\")";
            $this->insertDb($sql);
        }
        else {
            $sql = "UPDATE log_infos SET spend_time = '$spend_time' WHERE log_key = '$log_key'";
            $this->updateDb($sql);
        }
        
    }
    
    
    public function queryObjectDetailByUuid(
        $object_show_uuids,
        $user_id
        )
    {
        if (is_array($object_show_uuids) === false)
        {
            return false;
        }

        if (count($object_show_uuids) <= 0)
        {
            return false;
        }

        $sql = "select * from object_details where object_show_uuid in (";
                                foreach ($object_show_uuids as $show_uuid => $values)
        {
            $sql = $sql . "'{$show_uuid}',";
        }
                                $sql = substr($sql, 0, -1);
        $sql = $sql . ") and user_id={$user_id}";
        $sql .= " and is_delete!=1";         return $this->selectDb($sql);
    }

    
    public function queryChildObjectDetailByUuidAndName(
        $child_object_ids,
        $user_id
        )
    {
        if (count($child_object_ids) <= 0)
        {
            FXP::trace("queryChildObjectDetailByUuidAndName, child_object_ids is null");
            return false;
        }

        $name = "";
        $parent_object_id = "";
        $sql = 'select * from object_details where name in (';
        foreach ($child_object_ids as $key => $object_detail)
        {
                                                if (isset($object_detail->parent_object_id) == false)
            {
                continue;
            }
            $name = $name . '"' . $object_detail->name .'",';
            $parent_object_id = $parent_object_id . "{$object_detail->parent_object_id},";
        }

                                $name = substr($name, 0, -1);
        $parent_object_id = substr($parent_object_id, 0, -1);
                                if ($name == "" || $parent_object_id == "")
        {
                        return array();
        }

        $sql = $sql . $name .") and parent_object_id in (";
        $sql = $sql . $parent_object_id . ") and user_id={$user_id}";
        $sql .= " and is_delete!=1";         FXP::trace("queryChildObjectDetailByUuidAndName, sql:$sql");
        return $this->selectDb($sql);
    }
    
    
    public function batchCreateObjectDetails(
        $up_create_actions,
        $user
        )
    {
        if (count($up_create_actions) <= 0 ||
            ($user instanceof MUser) === false)
        {
            return false;
        }

        $name = "";
        $parent_object_id = "";
        $sql  = "insert into object_details(user_id,object_type,parent_object_id,";
        $sql .= "create_time,update_time,name,object_show_uuid,current_version_id,";
        $sql .= "current_object_size,current_event_show_uuid,custom_property,";
        $sql .= "created_at,updated_at) values ";
        foreach ($up_create_actions as $key => $object_detail)
        {
                                                $object_detail->object_show_uuid        = 
                MUtils::random_string(MConst::LEN_OBJECT_UUID);
            $object_detail->current_event_show_uuid = 
                MUtils::random_string(MConst::LEN_EVENT_UUID);
            if (isset($object_detail->current_version_id) === false)
                $object_detail->current_version_id = 0; 

            $current_time = MUtils::getCurrentTime();
            $object_detail->custom_property  = "{\"object_history_info\":[{";
            $object_detail->custom_property .= "\"type\":$object_detail->object_type,";
            $object_detail->custom_property .= "\"object_version_id\":{$object_detail->current_version_id},";
            $object_detail->custom_property .= "\"user_id\":{$user->user_id},";
            $object_detail->custom_property .= "\"user_nick\":\"{$user->nick}\",";
            $object_detail->custom_property .= "\"datetime\":\"{$current_time}\"}],";
            $object_detail->custom_property .= "\"root_object_id\":";

            $sql .= "({$user->user_id},$object_detail->object_type,";
            $sql .= "{$object_detail->parent_object_id},";
            $sql .= "{$object_detail->create_time},";
            $sql .= "{$object_detail->modify_time},";
            $sql .= "\"{$object_detail->name}\",";
            $sql .= "'{$object_detail->object_show_uuid}',";
            $sql .= "{$object_detail->current_version_id},";
            $sql .= "{$object_detail->size},";
            $sql .= "'{$object_detail->current_event_show_uuid}',";
            $sql .= "'{$object_detail->custom_property}',";
            $sql .= "now(),now()),";
        }

                                $sql = substr($sql, 0, -1);

        $result = mysql_query($sql, $this->con);
        if ($result === false)
        {
            return false;
        }
        $rows = mysql_affected_rows(); 
        if ($rows <= 0)
        {
            return false;
        }

        $sql  = "UPDATE object_details ";
        $sql .= "SET custom_property = concat(custom_property,id,'}') ";
        $sql .= "WHERE user_id={$user->user_id} ";
        $sql .= "order by id desc limit {$rows}";
        $result = mysql_query($sql, $this->con);
        if ($result === false)
        {
            return false;
        }
        
        return true;
    }
    
    
    
    public function queryChildObjectDetailByParentidAndUserid(
        $child_object_ids,
        $user_id
        )
    {
        if (count($child_object_ids) <= 0)
        {
            FXP::trace("function: '{__FUNCTION__}',child_object_ids is null");
            return false;
        }

        $parent_object_id = "";
        $sql = 'select * from object_details where ';
        foreach ($child_object_ids as $key => $object_detail)
        {
            $parent_object_id = $parent_object_id . "{$object_detail->parent_object_id},";
        }
                                $parent_object_id = substr($parent_object_id, 0, -1);
        $sql = $sql ."parent_object_id in (";
        $sql = $sql . $parent_object_id . ") and user_id={$user_id}";
        $sql .= " and is_delete!=1";         FXP::trace("function: '{__FUNCTION__}',sql:'{$sql}'");
        return $this->selectDb($sql);
    }
    
    
    public function queryObjectVersionById($object_details)
    {
        if (count($object_details) <= 0)
        {
            FXP::trace("object_details is null");
            return false;
        }

        $id = "";
        $sql = 'select * from object_versions where ';
        foreach ($object_details as $key => $object_detail)
        {
            if ($object_detail->current_version_id == 0)
            {
                continue;
            }
            $id = $id . "{$object_detail->current_version_id},";
        }
                                $id = substr($id, 0, -1);
        $sql = $sql ."id in (";
        $sql = $sql . $id . ")";
        FXP::trace("queryObjectVersionById : sql:'{$sql}'");
        return $this->selectDb($sql);
    }
    
    
    public function queryLastedEventByUserId($user_id)
    {
        if ($user_id == "")
        {
            FXP::trace("function: '{__FUNCTION__}',user_id:'{$user_id}'");
            return false;
        }
        $sql = "select * from events where user_id={$user_id} order by id desc LIMIT 1";
        FXP::trace("function: '{__FUNCTION__}',sql:'{$sql}'");
        return $this->selectDb($sql);
    }
    
    
    public function queryBlockById($total_block_ids)
    {
        if ($total_block_ids == "")
        {
            FXP::trace("function: '{__FUNCTION__}',total_block_ids is null");
            return array();
        }
        $sql = "select * from object_blocks where id in ({$total_block_ids})";
        FXP::trace("function: 'queryBlockById',sql:'{$sql}'");
        return $this->selectDb($sql);
    }
    
    
    public function queryObjectDetailById($object_details)
    {
        if (count($object_details) <= 0)
        {
            FXP::trace("function: '{__FUNCTION__}',child_object_ids is null");
            return array();
        }

        $object_id = "";
        $sql = 'select * from object_details where ';
        foreach ($object_details as $key => $object_detail)
        {
            $object_id = $object_id . "{$object_detail->parent_object_id},";
        }
                                $object_id = substr($object_id, 0, -1);
        $sql = $sql ."id in (";
        $sql = $sql . $object_id . ")";
        FXP::trace("function: '{__FUNCTION__}',sql:'{$sql}'");
        return $this->selectDb($sql);
    }
}

?>